package net.haier.fashion.trend.report.util;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import org.slf4j.MDC;

import java.util.concurrent.ConcurrentHashMap;

public class ThreadLocalUtil {
    private static final TransmittableThreadLocal<ConcurrentHashMap<String, String>> context = new TransmittableThreadLocal<>();

    private ThreadLocalUtil() {
    }

    public static void bind(String key, String data) {
        ConcurrentHashMap<String, String> map = context.get();
        if (ObjectUtil.isNull(map)) {
            map = new ConcurrentHashMap<>();
        }
        map.put(key, data);
        context.set(map);
    }

    public static String get(String key) {
        ConcurrentHashMap<String, String> map = context.get();
        if (ObjectUtil.isNull(map)) {
            map = new ConcurrentHashMap<>();
        }
        return map.get(key);
    }

    public static void unbind() {
        context.remove();
    }

    public static void getAndSetTraceId() {
        String tcId = get("tcId");
        tcId = StrUtil.blankToDefault(tcId, IdUtil.getSnowflakeNextIdStr());
        bind("tcId", tcId);
        MDC.put("tcId", tcId);
    }

    public static void clearTraceId() {
        MDC.remove("tcId");
        unbind();
    }
}
